<script>
import ImageInput from "./ImageInput.vue";

import { notEmpty } from "./utils";

export default {
  components: {
    ImageInput,
  },
  data() {
    return {
      formData: {
        avatar: "",
        username: "",
        password: "",
        confirmPassword: "",
        nickname: "",
      },
      errMsg: "",
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value !== this.formData.password) {
                callback(new Error("两次输入密码不一致!"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { max: 50, message: "长度不能超过 50 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async submit() {
      try {
        await this.$refs.form.validate();
        // 实现文件上传
        const formData = new FormData();
        // 将 this.formData 转换为 formData
        Object.entries(this.formData).forEach(([key, value]) => {
          if (key === "avatar" && value instanceof File) {
            formData.append(key, value, value.name);
          } else formData.append(key, value);
        });
        // 发起请求
        const { data } = await this.$request("/register", {
          method: "post",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          data: formData,
        });
        if (data.success) {
          // 执行注册成功后的操作
          this.$emit("toggle");
        } else {
          // 执行注册失败后的操作
          if (notEmpty(data.errors)) {
            this.errMsg = data.errors.username.join(", ");
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
  computed: {
    avatar: {
      get() {
        return `https://api.multiavatar.com/${this.formData.nickname}.png`;
      },
      set(val) {
        this.formData.avatar = val;
      },
    },
  },
  watch: {
    "formData.nickname"(val) {
      this.formData.avatar = `/multi-avatar/${val}.svg`;
    },
  },
};
</script>
<template>
  <ElForm
    ref="form"
    :model="formData"
    :rules="rules"
    label-position="left"
    label-width="120px"
    status-icon
  >
    <ElFormItem>
      <ImageInput class="w-48 h-48 rounded-lg" v-model="formData.avatar" />
    </ElFormItem>
    <ElFormItem label="用户名" prop="username" :error="errMsg">
      <ElInput v-model="formData.username" />
    </ElFormItem>
    <ElFormItem label="密码" prop="password">
      <ElInput type="password" v-model="formData.password" />
    </ElFormItem>
    <ElFormItem label="确认密码" prop="confirmPassword">
      <ElInput type="password" v-model="formData.confirmPassword" />
    </ElFormItem>
    <ElFormItem label="昵称" prop="nickname">
      <ElInput v-model="formData.nickname" />
    </ElFormItem>
    <ElFormItem>
      <ElButton @click="submit">注册</ElButton>
      <ElButton type="primary" link @click="$emit('toggle')">前往登录</ElButton>
    </ElFormItem>
  </ElForm>
</template>